// V-backend/src/controllers/adminController.js
const db = require('../models');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 权限检查工具函数
const checkPermission = (req, resourceAnchorId) => {
  const currentUser = req.user;
  const isSuperAdmin = currentUser.role === 'super_admin';
  const isOwner = currentUser.anchor_id === resourceAnchorId;
  
  return {
    hasPermission: isSuperAdmin || isOwner,
    isSuperAdmin,
    isOwner
  };
};

// ========== 商品图片上传配置 ==========
// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads/products');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'product-' + uniqueSuffix + ext);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件！'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});
// ========== 商品图片上传配置结束 ==========

const adminController = {
  // 获取仪表板统计数据 - 修复MySQL兼容性
  getDashboardStats: async (req, res) => {
    try {
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('📊 获取仪表板数据，主播ID:', anchorId, '角色:', userRole);
      
      // 构建查询条件
      let activityWhere = {};
      let productWhere = {};
      
      // 如果不是超级管理员，只查询自己的数据
      if (userRole !== 'super_admin') {
        activityWhere.anchor_id = anchorId;
        productWhere.anchor_id = anchorId;
      }
      
      // 获取活动数量
      const activityCount = await db.Activity.count({ 
        where: activityWhere 
      });
      
      // 获取商品数量
      const productCount = await db.Product.count({ 
        where: productWhere 
      });
      
      // 获取订单数量 - 使用原生SQL查询
      let orderCount = 0;
      try {
        let orderQuery = `
          SELECT COUNT(DISTINCT oi.order_id) as order_count
          FROM v_order_item oi 
          JOIN v_product p ON oi.product_id = p.product_id 
        `;
        
        // 如果不是超级管理员，添加权限限制
        if (userRole !== 'super_admin') {
          orderQuery += ` WHERE p.anchor_id = ?`;
        }
        
        const orderCountResult = await db.sequelize.query(orderQuery, {
          replacements: userRole !== 'super_admin' ? [anchorId] : [],
          type: db.Sequelize.QueryTypes.SELECT
        });
        orderCount = orderCountResult[0]?.order_count || 0;
      } catch (error) {
        console.log('⚠️ 订单数量查询失败，使用默认值0:', error.message);
        orderCount = 0;
      }
      
      // 获取总销售额 - 使用原生SQL查询
      let totalSales = 0;
      try {
        let salesQuery = `
          SELECT SUM(oi.subtotal) as total_sales
          FROM v_order_item oi 
          JOIN v_product p ON oi.product_id = p.product_id 
        `;
        
        // 如果不是超级管理员，添加权限限制
        if (userRole !== 'super_admin') {
          salesQuery += ` WHERE p.anchor_id = ?`;
        }
        
        const totalSalesResult = await db.sequelize.query(salesQuery, {
          replacements: userRole !== 'super_admin' ? [anchorId] : [],
          type: db.Sequelize.QueryTypes.SELECT
        });
        totalSales = parseFloat(totalSalesResult[0]?.total_sales || 0);
      } catch (error) {
        console.log('⚠️ 销售额查询失败，使用默认值0:', error.message);
        totalSales = 0;
      }
      
      // 获取最近活动
      let recentActivitiesWhere = {};
      if (userRole !== 'super_admin') {
        recentActivitiesWhere.anchor_id = anchorId;
      }
      
      const recentActivities = await db.Activity.findAll({
        where: recentActivitiesWhere,
        include: [{
          model: db.Anchor,
          as: 'anchor',
          attributes: ['anchor_name']
        }],
        order: [['created_at', 'DESC']],
        limit: 5
      });
      
      // 获取最近订单 - 简化处理
      let recentOrders = [];
      try {
        let recentOrdersQuery = `
          SELECT o.order_id, o.order_number, o.total_amount, o.status, o.created_at,
                 a.audience_name
          FROM v_order o
          JOIN v_audience a ON o.audience_id = a.audience_id
        `;
        
        // 如果不是超级管理员，添加权限限制
        if (userRole !== 'super_admin') {
          recentOrdersQuery += `
            WHERE EXISTS (
              SELECT 1 FROM v_order_item oi 
              JOIN v_product p ON oi.product_id = p.product_id 
              WHERE p.anchor_id = ? AND oi.order_id = o.order_id
            )
          `;
        }
        
        recentOrdersQuery += ` ORDER BY o.created_at DESC LIMIT 5`;
        
        const recentOrdersResult = await db.sequelize.query(recentOrdersQuery, {
          replacements: userRole !== 'super_admin' ? [anchorId] : [],
          type: db.Sequelize.QueryTypes.SELECT
        });
        
        recentOrders = recentOrdersResult.map(order => ({
          order_id: order.order_id,
          order_number: order.order_number,
          total_amount: order.total_amount,
          status: order.status,
          audience: { username: order.audience_name }
        }));
      } catch (error) {
        console.log('⚠️ 最近订单查询失败，使用空数组:', error.message);
        recentOrders = [];
      }

      // 今日数据统计
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      // 今日新增预约
      let todayRegistrations = 0;
      try {
        let registrationWhere = {
          created_at: {
            [db.Sequelize.Op.gte]: today
          }
        };
        
        // 如果不是超级管理员，添加权限限制
        if (userRole !== 'super_admin') {
          todayRegistrations = await db.Registration.count({
            where: registrationWhere,
            include: [{
              model: db.Activity,
              as: 'activity',
              where: { anchor_id: anchorId }
            }]
          });
        } else {
          todayRegistrations = await db.Registration.count({
            where: registrationWhere
          });
        }
      } catch (error) {
        console.log('⚠️ 今日预约查询失败，使用默认值0:', error.message);
        todayRegistrations = 0;
      }
      
      // 今日新增订单
      let todayOrders = 0;
      try {
        let todayOrdersQuery = `
          SELECT COUNT(DISTINCT oi.order_id) as today_orders
          FROM v_order_item oi 
          JOIN v_product p ON oi.product_id = p.product_id 
          JOIN v_order o ON oi.order_id = o.order_id
          WHERE o.created_at >= ?
        `;
        
        // 如果不是超级管理员，添加权限限制
        if (userRole !== 'super_admin') {
          todayOrdersQuery += ` AND p.anchor_id = ?`;
        }
        
        const todayOrdersResult = await db.sequelize.query(todayOrdersQuery, {
          replacements: userRole !== 'super_admin' ? [today, anchorId] : [today],
          type: db.Sequelize.QueryTypes.SELECT
        });
        
        todayOrders = todayOrdersResult[0]?.today_orders || 0;
      } catch (error) {
        console.log('⚠️ 今日订单查询失败，使用默认值0:', error.message);
        todayOrders = 0;
      }

      const dashboardData = {
        overview: {
          totalActivities: activityCount,
          totalProducts: productCount,
          totalOrders: orderCount,
          totalSales: totalSales.toFixed(2)
        },
        todayStats: {
          registrations: todayRegistrations,
          orders: todayOrders
        },
        recentActivities: recentActivities.map(activity => ({
          activity_id: activity.activity_id,
          title: activity.title,
          start_time: activity.start_time,
          status: activity.status,
          anchor: activity.anchor ? { name: activity.anchor.anchor_name } : null
        })),
        recentOrders: recentOrders
      };

      console.log('✅ 仪表板数据返回成功');
      console.log('📊 数据统计:', {
        activities: activityCount,
        products: productCount,
        orders: orderCount,
        sales: totalSales,
        todayRegistrations,
        todayOrders
      });

      res.json({
        success: true,
        data: dashboardData
      });
    } catch (error) {
      console.error('❌ 获取仪表板数据失败:', error);
      
      // 即使出错也返回基础数据
      const fallbackData = {
        overview: {
          totalActivities: 0,
          totalProducts: 0,
          totalOrders: 0,
          totalSales: '0.00'
        },
        todayStats: {
          registrations: 0,
          orders: 0
        },
        recentActivities: [],
        recentOrders: []
      };
      
      res.json({
        success: true,
        data: fallbackData
      });
    }
  },

  // 获取活动列表 - 超级管理员可以看到所有活动
  getActivities: async (req, res) => {
    try {
      const { page = 1, limit = 10, status, search } = req.query;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('🔍 当前用户:', { anchorId, role: userRole });
      console.log('🔍 活动搜索参数:', { page, limit, status, search });
      
      // 构建查询条件
      const where = {};
      
      // 如果不是超级管理员，只查询自己的活动
      if (userRole !== 'super_admin') {
        where.anchor_id = anchorId;
      }
      
      if (status && status !== '') where.status = status;
      if (search && search !== '') {
        where[db.Sequelize.Op.or] = [
          { title: { [db.Sequelize.Op.like]: `%${search}%` } },
          { description: { [db.Sequelize.Op.like]: `%${search}%` } }
        ];
      }
      
      console.log('📋 活动查询条件:', JSON.stringify(where, null, 2));
      
      const activities = await db.Activity.findAndCountAll({
        where,
        include: [{
          model: db.Anchor,
          as: 'anchor',
          attributes: ['anchor_name', 'role']
        }],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: (page - 1) * limit
      });
    
      console.log('✅ 活动查询结果 - 总数:', activities.count);
      
      res.json({
        success: true,
        data: {
          activities: activities.rows,
          pagination: {
            total: activities.count,
            current: parseInt(page),
            pageSize: parseInt(limit),
            totalPages: Math.ceil(activities.count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取活动列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取活动列表失败: ' + error.message
      });
    }
  },

  // 获取单个活动详情
  getActivityById: async (req, res) => {
    try {
      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('🔍 获取活动详情:', { id, anchorId, role: userRole });
      
      // 构建查询条件
      const where = { activity_id: id };
      
      // 如果不是超级管理员，只能查看自己的活动
      if (userRole !== 'super_admin') {
        where.anchor_id = anchorId;
      }
      
      const activity = await db.Activity.findOne({
        where,
        include: [{
          model: db.Anchor,
          as: 'anchor',
          attributes: ['anchor_name']
        }]
      });
      
      if (!activity) {
        return res.status(404).json({
          success: false,
          message: '活动不存在或无权访问'
        });
      }
      
      console.log('✅ 活动详情获取成功');
      
      res.json({
        success: true,
        data: activity
      });
    } catch (error) {
      console.error('获取活动详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取活动详情失败: ' + error.message
      });
    }
  },

  // 创建活动
  createActivity: async (req, res) => {
    try {
      const anchorId = req.user.anchor_id;
      const {
        title,
        description,
        start_time,
        end_time,
        location,
        max_participants
      } = req.body;

      console.log('🎯 创建活动请求:', {
        anchorId,
        title,
        description,
        start_time,
        end_time,
        location,
        max_participants,
        fullBody: req.body
      });

      // 验证必要字段
      if (!title || !start_time || !end_time) {
        return res.status(400).json({
          success: false,
          message: '活动标题、开始时间和结束时间为必填项'
        });
      }

      // 创建活动 - 修复字段映射
      const activity = await db.Activity.create({
        anchor_id: anchorId,
        title: title,
        description: description || '',
        start_time: new Date(start_time),
        end_time: new Date(end_time),
        location: location || '线上',
        max_participants: max_participants || 100,
        current_participants: 0,
        status: 'pending',
        created_at: new Date(),
        updated_at: new Date()
      });

      console.log('✅ 活动创建成功:', activity.activity_id);

      res.json({
        success: true,
        message: '活动创建成功',
        data: activity
      });
    } catch (error) {
      console.error('❌ 创建活动失败:', error);
      console.error('❌ 错误详情:', error.message);
      console.error('❌ 错误堆栈:', error.stack);
      
      res.status(500).json({
        success: false,
        message: '创建活动失败: ' + error.message
      });
    }
  },

  // 更新活动信息 - 添加权限检查
  updateActivity: async (req, res) => {
    try {
      const { id } = req.params;
      const {
        title,
        description,
        start_time,
        end_time,
        location,
        max_participants,
        status
      } = req.body;

      console.log('✏️ 更新活动请求:', { 
        id, 
        user: req.user, 
        title,
        body: req.body 
      });

      // 查找活动
      const activity = await db.Activity.findOne({
        where: { activity_id: id }
      });
      
      if (!activity) {
        console.log('❌ 活动不存在，ID:', id);
        return res.status(404).json({
          success: false,
          message: '活动不存在'
        });
      }

      console.log('🔍 找到活动:', {
        activity_id: activity.activity_id,
        title: activity.title,
        anchor_id: activity.anchor_id,
        current_user: req.user.anchor_id,
        user_role: req.user.role
      });

      // 权限检查
      const permission = checkPermission(req, activity.anchor_id);
      console.log('🔐 权限检查结果:', permission);
      
      if (!permission.hasPermission) {
        console.log('❌ 权限不足:', {
          activity_owner: activity.anchor_id,
          current_user: req.user.anchor_id,
          user_role: req.user.role,
          permission
        });
        return res.status(403).json({
          success: false,
          message: '权限不足，只能修改自己创建的活动'
        });
      }

      console.log('✅ 权限检查通过:', permission);

      // 更新活动信息
      const updateData = {};
      if (title !== undefined) updateData.title = title;
      if (description !== undefined) updateData.description = description;
      if (start_time !== undefined) updateData.start_time = new Date(start_time);
      if (end_time !== undefined) updateData.end_time = new Date(end_time);
      if (location !== undefined) updateData.location = location;
      if (max_participants !== undefined) updateData.max_participants = max_participants;
      if (status !== undefined) updateData.status = status;

      console.log('📝 准备更新的数据:', updateData);

      await activity.update(updateData);

      console.log('✅ 活动更新成功:', id);

      res.json({
        success: true,
        message: '活动更新成功',
        data: activity
      });
    } catch (error) {
      console.error('❌ 更新活动失败:', error);
      res.status(500).json({
        success: false,
        message: '更新活动失败: ' + error.message
      });
    }
  },

  // 删除活动 - 添加权限检查
  deleteActivity: async (req, res) => {
    try {
      const { id } = req.params;
      
      console.log('🗑️ 删除活动请求:', { id, user: req.user });

      // 查找活动
      const activity = await db.Activity.findOne({
        where: { activity_id: id }
      });
      
      if (!activity) {
        return res.status(404).json({
          success: false,
          message: '活动不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, activity.anchor_id);
      if (!permission.hasPermission) {
        console.log('❌ 权限不足，无法删除活动');
        return res.status(403).json({
          success: false,
          message: '权限不足，只能删除自己创建的活动'
        });
      }

      // 检查是否有预约记录
      const registrationCount = await db.Registration.count({
        where: { activity_id: id }
      });

      if (registrationCount > 0) {
        return res.status(400).json({
          success: false,
          message: '该活动已有用户预约，无法删除'
        });
      }

      // 删除活动
      await activity.destroy();

      console.log('✅ 活动删除成功:', id);

      res.json({
        success: true,
        message: '活动删除成功'
      });
    } catch (error) {
      console.error('删除活动失败:', error);
      res.status(500).json({
        success: false,
        message: '删除活动失败: ' + error.message
      });
    }
  },

  // 更新活动状态 - 添加权限检查
  updateActivityStatus: async (req, res) => {
    try {
      const { id } = req.params;
      const { status } = req.body;
      
      console.log('🔄 更新活动状态请求:', { id, status, user: req.user });

      // 查找活动
      const activity = await db.Activity.findOne({
        where: { activity_id: id }
      });
      
      if (!activity) {
        return res.status(404).json({
          success: false,
          message: '活动不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, activity.anchor_id);
      if (!permission.hasPermission) {
        console.log('❌ 权限不足，无法更新活动状态');
        return res.status(403).json({
          success: false,
          message: '权限不足，只能更新自己创建的活动状态'
        });
      }
      
      await activity.update({ status });
      
      res.json({
        success: true,
        message: '活动状态更新成功'
      });
    } catch (error) {
      console.error('更新活动状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新活动状态失败'
      });
    }
  },

  // 获取商品列表 - 添加权限检查
  getProducts: async (req, res) => {
    try {
      const { page = 1, limit = 10, status, search } = req.query;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('🔍 商品搜索参数:', { page, limit, status, search, anchorId, role: userRole });
      
      // 构建查询条件
      const where = {};
      
      // 如果不是超级管理员，只查询自己的商品
      if (userRole !== 'super_admin') {
        where.anchor_id = anchorId;
      }
      
      if (status && status !== '') where.status = status;
      if (search && search !== '') {
        where.product_name = { [db.Sequelize.Op.like]: `%${search}%` };
      }
      
      console.log('📦 商品查询条件:', where);
      
      const products = await db.Product.findAndCountAll({
        where,
        include: [{
          model: db.Anchor,
          as: 'anchor',
          attributes: ['anchor_name']
        }, {
          model: db.ProductImage,
          as: 'images'
        }],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: (page - 1) * limit
      });
      
      console.log('✅ 商品查询结果:', products.count);
      
      res.json({
        success: true,
        data: {
          products: products.rows,
          pagination: {
            total: products.count,
            current: parseInt(page),
            pageSize: parseInt(limit),
            totalPages: Math.ceil(products.count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取商品列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取商品列表失败: ' + error.message
      });
    }
  },

  // 获取单个商品详情
  getProductById: async (req, res) => {
    try {
      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      const userRole = req.user.role;
      
      console.log('🔍 获取商品详情:', { id, anchorId, role: userRole });
      
      // 构建查询条件
      const where = { product_id: id };
      
      // 如果不是超级管理员，只能查看自己的商品
      if (userRole !== 'super_admin') {
        where.anchor_id = anchorId;
      }
      
      const product = await db.Product.findOne({
        where,
        include: [{
          model: db.Anchor,
          as: 'anchor',
          attributes: ['anchor_name']
        }, {
          model: db.ProductImage,
          as: 'images',
          order: [['sort_order', 'ASC']]
        }]
      });
      
      if (!product) {
        return res.status(404).json({
          success: false,
          message: '商品不存在或无权访问'
        });
      }
      
      console.log('✅ 商品详情获取成功');
      
      res.json({
        success: true,
        data: product
      });
    } catch (error) {
      console.error('获取商品详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取商品详情失败: ' + error.message
      });
    }
  },

  // 创建商品
  createProduct: async (req, res) => {
    try {
      const anchorId = req.user.anchor_id;
      const {
        product_name,
        product_description,
        price,
        original_price,
        stock_quantity,
        category,
        cover_image
      } = req.body;

      console.log('🎯 创建商品请求:', {
        anchorId,
        product_name,
        price,
        stock_quantity,
        fullBody: req.body
      });

      // 验证必要字段
      if (!product_name || !price || stock_quantity === undefined) {
        return res.status(400).json({
          success: false,
          message: '商品名称、价格和库存为必填项'
        });
      }

      // 创建商品
      const product = await db.Product.create({
        anchor_id: anchorId,
        product_name: product_name,
        product_description: product_description || '',
        price: parseFloat(price),
        original_price: original_price ? parseFloat(original_price) : null,
        stock_quantity: parseInt(stock_quantity),
        category: category || '',
        status: 'active',
        cover_image: cover_image || '',
        created_at: new Date(),
        updated_at: new Date()
      });

      console.log('✅ 商品创建成功:', product.product_id);

      res.json({
        success: true,
        message: '商品创建成功',
        data: product
      });
    } catch (error) {
      console.error('❌ 创建商品失败:', error);
      console.error('❌ 错误详情:', error.message);
      
      res.status(500).json({
        success: false,
        message: '创建商品失败: ' + error.message
      });
    }
  },

  // 更新商品信息 - 添加权限检查
  updateProduct: async (req, res) => {
    try {
      const { id } = req.params;
      const {
        product_name,
        product_description,
        price,
        original_price,
        stock_quantity,
        category,
        cover_image,
        status
      } = req.body;

      console.log('✏️ 更新商品请求:', { 
        id, 
        user: req.user, 
        product_name,
        body: req.body 
      });

      // 查找商品
      const product = await db.Product.findOne({
        where: { product_id: id }
      });
      
      if (!product) {
        console.log('❌ 商品不存在，ID:', id);
        return res.status(404).json({
          success: false,
          message: '商品不存在'
        });
      }

      console.log('🔍 找到商品:', {
        product_id: product.product_id,
        product_name: product.product_name,
        anchor_id: product.anchor_id,
        current_user: req.user.anchor_id,
        user_role: req.user.role
      });

      // 权限检查
      const permission = checkPermission(req, product.anchor_id);
      console.log('🔐 权限检查结果:', permission);
      
      if (!permission.hasPermission) {
        console.log('❌ 权限不足:', {
          product_owner: product.anchor_id,
          current_user: req.user.anchor_id,
          user_role: req.user.role,
          permission
        });
        return res.status(403).json({
          success: false,
          message: '权限不足，只能修改自己创建的商品'
        });
      }

      console.log('✅ 权限检查通过:', permission);

      // 更新商品信息
      const updateData = {};
      if (product_name !== undefined) updateData.product_name = product_name;
      if (product_description !== undefined) updateData.product_description = product_description;
      if (price !== undefined) updateData.price = parseFloat(price);
      if (original_price !== undefined) updateData.original_price = original_price ? parseFloat(original_price) : null;
      if (stock_quantity !== undefined) updateData.stock_quantity = parseInt(stock_quantity);
      if (category !== undefined) updateData.category = category;
      if (cover_image !== undefined) updateData.cover_image = cover_image;
      if (status !== undefined) updateData.status = status;
      updateData.updated_at = new Date();

      console.log('📝 准备更新的数据:', updateData);

      await product.update(updateData);

      console.log('✅ 商品更新成功:', id);

      res.json({
        success: true,
        message: '商品更新成功',
        data: product
      });
    } catch (error) {
      console.error('❌ 更新商品失败:', error);
      res.status(500).json({
        success: false,
        message: '更新商品失败: ' + error.message
      });
    }
  },

  // 删除商品 - 添加权限检查
  deleteProduct: async (req, res) => {
    try {
      const { id } = req.params;
      
      console.log('🗑️ 删除商品请求:', { id, user: req.user });

      // 查找商品
      const product = await db.Product.findOne({
        where: { product_id: id }
      });
      
      if (!product) {
        return res.status(404).json({
          success: false,
          message: '商品不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, product.anchor_id);
      if (!permission.hasPermission) {
        console.log('❌ 权限不足，无法删除商品');
        return res.status(403).json({
          success: false,
          message: '权限不足，只能删除自己创建的商品'
        });
      }

      // 检查是否有订单记录
      const orderItemCount = await db.OrderItem.count({
        where: { product_id: id }
      });

      if (orderItemCount > 0) {
        return res.status(400).json({
          success: false,
          message: '该商品已有订单记录，无法删除'
        });
      }

      // 删除商品图片
      await db.ProductImage.destroy({
        where: { product_id: id }
      });

      // 删除商品
      await product.destroy();

      console.log('✅ 商品删除成功:', id);

      res.json({
        success: true,
        message: '商品删除成功'
      });
    } catch (error) {
      console.error('删除商品失败:', error);
      res.status(500).json({
        success: false,
        message: '删除商品失败: ' + error.message
      });
    }
  },

  // ========== 商品图片上传功能 ==========
  
  // 上传商品图片
  uploadProductImages: async (req, res) => {
  try {
    // 手动配置multer来处理文件上传
    const multer = require('multer');
    const path = require('path');
    const fs = require('fs');

    // 确保上传目录存在
    const uploadDir = path.join(__dirname, '../../uploads/products');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    // 配置multer存储
    const storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, uploadDir);
      },
      filename: function (req, file, cb) {
        // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = path.extname(file.originalname);
        cb(null, 'product-' + uniqueSuffix + ext);
      }
    });

    // 文件过滤器
    const fileFilter = (req, file, cb) => {
      // 只允许图片文件
      if (file.mimetype.startsWith('image/')) {
        cb(null, true);
      } else {
        cb(new Error('只允许上传图片文件！'), false);
      }
    };

    const upload = multer({
      storage: storage,
      fileFilter: fileFilter,
      limits: {
        fileSize: 5 * 1024 * 1024 // 限制5MB
      }
    }).array('file', 10); // 注意：字段名改为 'file'，这是Element Upload组件的默认字段名

    // 执行上传
    upload(req, res, async function (err) {
      if (err) {
        console.error('❌ 文件上传错误:', err);
        return res.status(500).json({
          success: false,
          message: '文件上传失败: ' + err.message
        });
      }

      const { id } = req.params;
      const anchorId = req.user.anchor_id;
      
      console.log('🖼️ 上传商品图片请求:', { 
        productId: id, 
        anchorId,
        files: req.files ? req.files.length : 0 
      });

      // 查找商品
      const product = await db.Product.findOne({
        where: { product_id: id }
      });
      
      if (!product) {
        // 删除已上传的文件
        if (req.files && req.files.length > 0) {
          req.files.forEach(file => {
            if (fs.existsSync(file.path)) {
              fs.unlinkSync(file.path);
            }
          });
        }
        return res.status(404).json({
          success: false,
          message: '商品不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, product.anchor_id);
      if (!permission.hasPermission) {
        // 删除已上传的文件
        if (req.files && req.files.length > 0) {
          req.files.forEach(file => {
            if (fs.existsSync(file.path)) {
              fs.unlinkSync(file.path);
            }
          });
        }
        return res.status(403).json({
          success: false,
          message: '权限不足，只能为自己创建的商品上传图片'
        });
      }

      if (!req.files || req.files.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请选择要上传的图片'
        });
      }

      const imageRecords = [];
      
      // 获取当前商品的最大排序值
      const maxSortOrder = await db.ProductImage.max('sort_order', {
        where: { product_id: id }
      }) || 0;

      // 创建图片记录
      for (let i = 0; i < req.files.length; i++) {
        const file = req.files[i];
        const imageUrl = `/uploads/products/${path.basename(file.path)}`;
        
        const imageRecord = await db.ProductImage.create({
          product_id: id,
          image_url: imageUrl,
          sort_order: maxSortOrder + i + 1,
          created_at: new Date()
        });
        
        imageRecords.push(imageRecord);
      }

      console.log('✅ 商品图片上传成功:', imageRecords.length, '张图片');

      res.json({
        success: true,
        message: `成功上传 ${imageRecords.length} 张图片`,
        data: imageRecords
      });
    });

  } catch (error) {
    console.error('❌ 上传商品图片失败:', error);
    res.status(500).json({
      success: false,
      message: '上传商品图片失败: ' + error.message
    });
  }
},

  // 删除商品图片
  deleteProductImage: async (req, res) => {
    try {
      const { imageId } = req.params;
      const anchorId = req.user.anchor_id;
      
      console.log('🗑️ 删除商品图片请求:', { imageId, anchorId });

      const productImage = await db.ProductImage.findByPk(imageId, {
        include: [{ model: db.Product, as: 'product' }]
      });
      
      if (!productImage) return res.status(404).json({ success: false, message: '图片不存在' });

      const permission = checkPermission(req, productImage.product.anchor_id);
      if (!permission.hasPermission) return res.status(403).json({ success: false, message: '权限不足' });

      const filePath = path.join(__dirname, '../..', productImage.image_url);
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);

      await productImage.destroy();
      console.log('✅ 商品图片删除成功:', imageId);
      res.json({ success: true, message: '图片删除成功' });
    } catch (error) {
      console.error('删除商品图片失败:', error);
      res.status(500).json({ success: false, message: '删除商品图片失败: ' + error.message });
    }
  },

  // 图片排序
  sortProductImages: async (req, res) => {
    try {
      const { id } = req.params;
      const { imageIds } = req.body;
      const anchorId = req.user.anchor_id;
      
      console.log('🔄 图片排序请求:', { productId: id, anchorId, imageIds });

      if (!imageIds || !Array.isArray(imageIds)) {
        return res.status(400).json({ success: false, message: '请提供图片ID数组' });
      }

      const product = await db.Product.findOne({ where: { product_id: id } });
      if (!product) return res.status(404).json({ success: false, message: '商品不存在' });

      const permission = checkPermission(req, product.anchor_id);
      if (!permission.hasPermission) return res.status(403).json({ success: false, message: '权限不足' });

      const updatePromises = imageIds.map((imageId, index) => {
        return db.ProductImage.update({ sort_order: index + 1 }, { where: { image_id: imageId, product_id: id } });
      });

      await Promise.all(updatePromises);
      console.log('✅ 图片排序成功');
      res.json({ success: true, message: '图片排序成功' });
    } catch (error) {
      console.error('图片排序失败:', error);
      res.status(500).json({ success: false, message: '图片排序失败: ' + error.message });
    }
  },

  // 设置封面图片
  setProductCover: async (req, res) => {
    try {
      const { imageId } = req.params;
      const anchorId = req.user.anchor_id;
      
      console.log('🖼️ 设置封面图片请求:', { imageId, anchorId });

      const productImage = await db.ProductImage.findByPk(imageId, {
        include: [{ model: db.Product, as: 'product' }]
      });
      
      if (!productImage) return res.status(404).json({ success: false, message: '图片不存在' });

      const permission = checkPermission(req, productImage.product.anchor_id);
      if (!permission.hasPermission) return res.status(403).json({ success: false, message: '权限不足' });

      await db.Product.update({ cover_image: productImage.image_url }, { where: { product_id: productImage.product_id } });
      console.log('✅ 封面图片设置成功');
      res.json({ success: true, message: '封面图片设置成功' });
    } catch (error) {
      console.error('设置封面图片失败:', error);
      res.status(500).json({ success: false, message: '设置封面图片失败: ' + error.message });
    }
  },
  // ========== 商品图片上传功能结束 ==========

  // 更新商品状态 - 添加权限检查
  updateProductStatus: async (req, res) => {
    try {
      const { id } = req.params;
      const { status } = req.body;
      
      console.log('🔄 更新商品状态请求:', { id, status, user: req.user });

      // 查找商品
      const product = await db.Product.findOne({
        where: { product_id: id }
      });
      
      if (!product) {
        return res.status(404).json({
          success: false,
          message: '商品不存在'
        });
      }

      // 权限检查
      const permission = checkPermission(req, product.anchor_id);
      if (!permission.hasPermission) {
        console.log('❌ 权限不足，无法更新商品状态');
        return res.status(403).json({
          success: false,
          message: '权限不足，只能更新自己创建的商品状态'
        });
      }
      
      await product.update({ status });
      
      res.json({
        success: true,
        message: '商品状态更新成功'
      });
    } catch (error) {
      console.error('更新商品状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新商品状态失败'
      });
    }
  },

  // 获取订单列表 - 支持更多筛选条件
getOrders: async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      order_number, 
      customer,
      start_date,
      end_date
    } = req.query;
    const anchorId = req.user.anchor_id;
    const userRole = req.user.role;
    
    console.log('📦 获取订单列表:', { 
      page, limit, status, order_number, customer, start_date, end_date,
      anchorId, role: userRole 
    });

    // 构建基础查询条件
    let orderWhere = {};
    let audienceWhere = {};
    
    if (status && status !== '') orderWhere.status = status;
    if (order_number && order_number !== '') {
      orderWhere.order_number = { [db.Sequelize.Op.like]: `%${order_number}%` };
    }
    if (customer && customer !== '') {
      audienceWhere.audience_name = { [db.Sequelize.Op.like]: `%${customer}%` };
    }
    
    // 日期筛选
    if (start_date && end_date) {
      orderWhere.created_at = {
        [db.Sequelize.Op.between]: [new Date(start_date), new Date(end_date + ' 23:59:59')]
      };
    }

    let orders;
    
    if (userRole === 'super_admin') {
      orders = await db.Order.findAndCountAll({
        where: orderWhere,
        include: [
          {
            model: db.OrderItem,
            as: 'items',
            include: [{
              model: db.Product,
              as: 'product',
              include: [{
                model: db.Anchor,
                as: 'anchor',
                attributes: ['anchor_name']
              }]
            }]
          },
          {
            model: db.Audience,
            as: 'audience',
            where: audienceWhere,
            attributes: ['audience_name', 'email']
          }
        ],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: (page - 1) * limit
      });
    } else {
      // 普通主播只能看到自己商品的订单
      orders = await db.Order.findAndCountAll({
        where: orderWhere,
        include: [
          {
            model: db.OrderItem,
            as: 'items',
            include: [{
              model: db.Product,
              as: 'product',
              where: { anchor_id: anchorId },
              include: [{
                model: db.Anchor,
                as: 'anchor',
                attributes: ['anchor_name']
              }]
            }]
          },
          {
            model: db.Audience,
            as: 'audience',
            where: audienceWhere,
            attributes: ['audience_name', 'email']
          }
        ],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: (page - 1) * limit
      });
    }
    
    console.log('✅ 订单查询结果:', orders.count);
    
    res.json({
      success: true,
      data: {
        orders: orders.rows,
        pagination: {
          total: orders.count,
          current: parseInt(page),
          pageSize: parseInt(limit),
          totalPages: Math.ceil(orders.count / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败: ' + error.message
    });
  }
},

  // 更新订单状态 - 添加权限检查
  updateOrderStatus: async (req, res) => {
    try {
      const { id } = req.params;
      const { status } = req.body;
      const userRole = req.user.role;
      
      console.log('🔄 更新订单状态请求:', { id, status, user: req.user });

      let order;
      
      // 如果是超级管理员，可以直接更新
      if (userRole === 'super_admin') {
        order = await db.Order.findByPk(id);
      } else {
        // 普通主播只能更新自己商品的订单
        order = await db.Order.findByPk(id, {
          include: [{
            model: db.OrderItem,
            as: 'items',
            include: [{
              model: db.Product,
              as: 'product',
              where: { anchor_id: req.user.anchor_id }
            }]
          }]
        });
      }
      
      if (!order || (userRole !== 'super_admin' && (!order.items || order.items.length === 0))) {
        return res.status(404).json({
          success: false,
          message: '订单不存在或无权操作'
        });
      }
      
      await order.update({ status });
      
      res.json({
        success: true,
        message: '订单状态更新成功'
      });
    } catch (error) {
      console.error('更新订单状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新订单状态失败'
      });
    }
  },

  // 获取用户列表
  getUsers: async (req, res) => {
    try {
      const { page = 1, limit = 10 } = req.query;
      
      const users = await db.Audience.findAndCountAll({
        attributes: { exclude: ['password'] },
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: (page - 1) * limit
      });
      
      res.json({
        success: true,
        data: {
          users: users.rows,
          pagination: {
            total: users.count,
            current: parseInt(page),
            pageSize: parseInt(limit),
            totalPages: Math.ceil(users.count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取用户列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户列表失败'
      });
    }
  },

  // 获取主播列表
  getAnchors: async (req, res) => {
    try {
      const { page = 1, limit = 10 } = req.query;
      
      const anchors = await db.Anchor.findAndCountAll({
        attributes: { exclude: ['password'] },
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: (page - 1) * limit
      });
      
      res.json({
        success: true,
        data: {
          anchors: anchors.rows,
          pagination: {
            total: anchors.count,
            current: parseInt(page),
            pageSize: parseInt(limit),
            totalPages: Math.ceil(anchors.count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取主播列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取主播列表失败'
      });
    }
  },

  // 获取管理员个人信息
  getAdminProfile: async (req, res) => {
    try {
      const anchor = await db.Anchor.findByPk(req.user.anchor_id, {
        attributes: { exclude: ['password'] }
      });
      
      if (!anchor) {
        return res.status(404).json({ 
          success: false,
          message: '用户不存在' 
        });
      }
      
      res.json({
        success: true,
        data: anchor
      });
    } catch (error) {
      console.error('获取管理员信息失败:', error);
      res.status(500).json({
        success: false,
        message: '获取用户信息失败'
      });
    }
  },
  // 获取订单详情 - 新增方法
getOrderById: async (req, res) => {
  try {
    const { id } = req.params;
    const anchorId = req.user.anchor_id;
    const userRole = req.user.role;
    
    console.log('🔍 获取订单详情:', { id, anchorId, role: userRole });

    let order;
    
    // 构建查询条件
    if (userRole === 'super_admin') {
      order = await db.Order.findByPk(id, {
        include: [
          {
            model: db.OrderItem,
            as: 'items',
            include: [{
              model: db.Product,
              as: 'product',
              include: [{
                model: db.Anchor,
                as: 'anchor',
                attributes: ['anchor_name']
              }]
            }]
          },
          {
            model: db.Audience,
            as: 'audience',
            attributes: ['audience_name', 'email']
          }
        ]
      });
    } else {
      // 普通主播只能查看自己商品的订单
      order = await db.Order.findByPk(id, {
        include: [
          {
            model: db.OrderItem,
            as: 'items',
            include: [{
              model: db.Product,
              as: 'product',
              where: { anchor_id: anchorId },
              include: [{
                model: db.Anchor,
                as: 'anchor',
                attributes: ['anchor_name']
              }]
            }]
          },
          {
            model: db.Audience,
            as: 'audience',
            attributes: ['audience_name', 'email']
          }
        ]
      });
    }
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在或无权访问'
      });
    }

    console.log('✅ 订单详情获取成功');

    res.json({
      success: true,
      data: order
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败: ' + error.message
    });
  }
},

// 获取订单统计 - 修复版本
getOrderStats: async (req, res) => {
  try {
    const anchorId = req.user.anchor_id;
    const userRole = req.user.role;
    
    console.log('📊 获取订单统计:', { anchorId, role: userRole });

    // 方法1: 使用原生SQL查询统计订单状态和金额
    let statusStatsQuery = `
      SELECT 
        o.status,
        COUNT(DISTINCT o.order_id) as order_count,
        SUM(oi.subtotal) as total_amount
      FROM v_order o
      JOIN v_order_item oi ON o.order_id = oi.order_id
      JOIN v_product p ON oi.product_id = p.product_id
      ${userRole !== 'super_admin' ? 'WHERE p.anchor_id = ?' : ''}
      GROUP BY o.status
    `;

    const statusStatsResult = await db.sequelize.query(statusStatsQuery, {
      replacements: userRole !== 'super_admin' ? [anchorId] : [],
      type: db.Sequelize.QueryTypes.SELECT
    });

    // 构建状态统计对象
    const statusStats = {};
    const allStatuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled', 'refunded'];
    
    // 初始化所有状态
    allStatuses.forEach(status => {
      statusStats[status] = {
        order_count: 0,
        total_amount: 0
      };
    });

    // 填充实际数据
    statusStatsResult.forEach(stat => {
      if (stat.status && statusStats[stat.status]) {
        statusStats[stat.status] = {
          order_count: parseInt(stat.order_count) || 0,
          total_amount: parseFloat(stat.total_amount) || 0
        };
      }
    });

    // 方法2: 统计总订单和总销售额
    let totalStatsQuery = `
      SELECT 
        COUNT(DISTINCT o.order_id) as total_orders,
        SUM(oi.subtotal) as total_sales
      FROM v_order o
      JOIN v_order_item oi ON o.order_id = oi.order_id
      JOIN v_product p ON oi.product_id = p.product_id
      ${userRole !== 'super_admin' ? 'WHERE p.anchor_id = ?' : ''}
    `;

    const totalStatsResult = await db.sequelize.query(totalStatsQuery, {
      replacements: userRole !== 'super_admin' ? [anchorId] : [],
      type: db.Sequelize.QueryTypes.SELECT
    });

    // 方法3: 今日统计
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    let todayStatsQuery = `
      SELECT 
        COUNT(DISTINCT o.order_id) as today_orders,
        SUM(oi.subtotal) as today_sales
      FROM v_order o
      JOIN v_order_item oi ON o.order_id = oi.order_id
      JOIN v_product p ON oi.product_id = p.product_id
      WHERE o.created_at >= ?
      ${userRole !== 'super_admin' ? 'AND p.anchor_id = ?' : ''}
    `;

    const todayStatsResult = await db.sequelize.query(todayStatsQuery, {
      replacements: userRole !== 'super_admin' ? [today, anchorId] : [today],
      type: db.Sequelize.QueryTypes.SELECT
    });

    // 构建返回数据
    const statsData = {
      statusStats: statusStats,
      todayStats: {
        orders: parseInt(todayStatsResult[0]?.today_orders) || 0,
        sales: parseFloat(todayStatsResult[0]?.today_sales) || 0
      },
      totalStats: {
        orders: parseInt(totalStatsResult[0]?.total_orders) || 0,
        sales: parseFloat(totalStatsResult[0]?.total_sales) || 0
      }
    };

    console.log('✅ 订单统计获取成功:', statsData);

    res.json({
      success: true,
      data: statsData
    });
  } catch (error) {
    console.error('❌ 获取订单统计失败:', error);
    
    // 返回基础的空数据，避免前端报错
    const fallbackData = {
      statusStats: {
        pending: { order_count: 0, total_amount: 0 },
        paid: { order_count: 0, total_amount: 0 },
        shipped: { order_count: 0, total_amount: 0 },
        completed: { order_count: 0, total_amount: 0 },
        cancelled: { order_count: 0, total_amount: 0 },
        refunded: { order_count: 0, total_amount: 0 }
      },
      todayStats: {
        orders: 0,
        sales: 0
      },
      totalStats: {
        orders: 0,
        sales: 0
      }
    };
    
    res.json({
      success: true,
      data: fallbackData
    });
  }
},

// 批量更新订单状态 - 新增方法
bulkUpdateOrderStatus: async (req, res) => {
  try {
    const { orderIds, status } = req.body;
    const userRole = req.user.role;
    
    console.log('🔄 批量更新订单状态:', { orderIds, status, user: req.user });

    if (!orderIds || !Array.isArray(orderIds) || orderIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的订单ID列表'
      });
    }

    let updateCount = 0;
    
    for (const orderId of orderIds) {
      let order;
      
      if (userRole === 'super_admin') {
        order = await db.Order.findByPk(orderId);
      } else {
        // 普通主播只能更新自己商品的订单
        order = await db.Order.findByPk(orderId, {
          include: [{
            model: db.OrderItem,
            as: 'items',
            include: [{
              model: db.Product,
              as: 'product',
              where: { anchor_id: req.user.anchor_id }
            }]
          }]
        });
      }
      
      if (order && (userRole === 'super_admin' || (order.items && order.items.length > 0))) {
        await order.update({ status });
        updateCount++;
      }
    }

    console.log('✅ 批量更新完成:', updateCount, '个订单');

    res.json({
      success: true,
      message: `成功更新 ${updateCount} 个订单状态`,
      data: { updatedCount: updateCount }
    });
  } catch (error) {
    console.error('批量更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '批量更新订单状态失败: ' + error.message
    });
  }
}
};

module.exports = adminController;